package com.example.config;

import com.example.entity.Sentence;
import com.example.service.SentenceService;
import com.example.textToVoice.TextToVoice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

@EnableWebMvc
@SpringBootConfiguration
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private SentenceService sentenceService;
    @Autowired
    private MyService myService;

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/toLogin").setViewName("login");

    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        File dest = new File(myService.getStandardAudioPath() + "/" + "test.mp3");
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
            List<Sentence> sentences = sentenceService.getAllSentences();
            Iterator<Sentence> iterator = sentences.iterator();
            while(iterator.hasNext()){
                Sentence sentence = iterator.next();
                try {
                    TextToVoice.textToVoice(sentence.getContent(), sentence.getId(), myService.getStandardAudioPath());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        registry.addResourceHandler("/sentence/getStandardAudio/**").addResourceLocations("file:" + myService.getStandardAudioPath() + "/");
    }

}
